package com.hmsg.health.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.hmsg.health.bean.Dto.UmengExtra;
import com.hmsg.health.bean.domain.MessageDo;
import com.hmsg.health.bean.domain.TaskDo;
import com.hmsg.health.bean.domain.UserAccountDo;
import com.hmsg.health.bean.domain.UserAccountRecordDo;
import com.hmsg.health.bean.domain.UserDo;
import com.hmsg.health.bean.domain.UserTaskDo;
import com.hmsg.health.dao.MessageDao;
import com.hmsg.health.dao.OrderDao;
import com.hmsg.health.dao.TaskDao;
import com.hmsg.health.dao.UserAccountDao;
import com.hmsg.health.dao.UserDao;
import com.hmsg.health.dao.UserTaskDao;
import com.hmsg.health.service.UserService;
import com.hmsg.health.utils.umeng.push.Demo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class Task {
    @Autowired
    private OrderDao orderDao;
    
   
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserAccountDao userAccountDao;
    @Autowired
    private TaskDao taskDao;
    
    @Autowired
    private UserTaskDao userTaskDao;
    
    @Autowired
    private MessageDao messageDao;
    
    @Autowired
    private UserService userService;
    @Autowired
    StringRedisTemplate stringTemplate;

  

    @Scheduled(cron = "0 */1 * * * ?")
    public void TaskJob() throws Exception {
       log.info("任务定时任务-----------------------");
       TaskDo t = new TaskDo();
       t.setTaskStatus(0);
       List<TaskDo> ts =  taskDao.select(t);
       
       //遍历所有正常的任务
       if(ts!=null&&ts.size()>0){
    	   for(TaskDo task:ts){
    		   
    		   Calendar start=Calendar.getInstance();
    		   start.setTime(task.getCreateTime());
    		   start.add(Calendar.MINUTE,task.getValidity());
    		   System.out.println(start.getTime());
    		   System.out.println(new Date());
    		   //如果任务到期
    		   if(new Date().after(start.getTime())){
    			  
    			  //如果该任务还有剩余数量
    			   if(task.getSurplusCount()>0){
    				   //将任务状态置为失效
    				   task.setTaskStatus(-1);
        			   taskDao.update(task);
        			   //返回金币
    				   UserAccountDo ua = userAccountDao.findUserAccount(task.getUser().getId());
    				   ua.setGlod(ua.getGlod()+task.getSurplusCount()*task.getTaskGold());
    				   userAccountDao.update(ua);
    				   
    				   //插入金币记录
    				   	UserAccountRecordDo uar = new UserAccountRecordDo();
	           			uar.setAmount(task.getSurplusCount()*task.getTaskGold());
	           			uar.setCreateTime(new Date());
	           			uar.setUserId(task.getUser().getId());
	           			uar.setGlodType(1);
	           			uar.setType(11);
	           			uar.setTitle("到期任务退回");
	           			userService.saveAccountRecord(uar);
	           			//查询是否有未审核的任务
    				   UserTaskDo ut = new UserTaskDo();
    				   ut.setTaskId(task.getId());
    				   ut.setStatus(1);
    				   List<UserTaskDo> list = userTaskDao.select(ut);
    				   MessageDo message = new MessageDo();
    				   	//如果没有未审核的任务直接发送消息
    				   if(list==null||list.size()<=0){
    					   	
	       	       			message.setCreateTime(new Date());
	       	       			message.setIsRead(0);
	       	       			message.setUserId(task.getUser().getId());
	       	       			if(task.getTypeDo()==null){
	       	       				message.setTitle("您好，您发布的"+task.getTaskName()+"到期自动关闭。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。");
	       	       			}else{
	       	       				message.setTitle("您好，您发布的"+task.getTypeDo().getName()+"到期自动关闭。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。");
	       	       			}
	       	       			
	       	       			message.setType(1);
	       	       			message.setResourceId(task.getId());
	       	       			
	       	       		//推送开始----------
        				if(task.getUser().getDeviceToken()!=null&&task.getUser().getDeviceToken().length()==64) {
        					Demo demo = new Demo();
        					
        					List<UmengExtra> list1 = new ArrayList<UmengExtra>();
        					UmengExtra ue = new UmengExtra();
        					ue.setKey("type");
        					ue.setValue(4);
        					list1.add(ue);
        					UmengExtra ue1 = new UmengExtra();
        					ue1.setKey("resourceId");
        					ue1.setValue(task.getId());
        					list1.add(ue1);
        					String text = "";
        					if(task.getTypeDo()==null){
        						text = "您好，您发布的"+task.getTaskName()+"到期自动关闭。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。";
                			}else{
                				text = "您好，您发布的"+task.getTypeDo().getName()+"到期自动关闭。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。";
                			}
        					JSONObject alert = new JSONObject();
        					alert.put("title", "任务到期");
        					//alert.put("subtitle", "任务到期通知");
        					alert.put("body", text);
        					demo.sendIOSUnicast(task.getUser().getDeviceToken(), alert,list1);
        				}
        				
        				if(task.getUser().getDeviceToken()!=null&&task.getUser().getDeviceToken().length()==44) {
        					Demo demo = new Demo();
        					List<UmengExtra> list1 = new ArrayList<UmengExtra>();
        					UmengExtra ue = new UmengExtra();
        					ue.setKey("type");
        					ue.setValue(4);
        					list1.add(ue);
        					UmengExtra ue1 = new UmengExtra();
        					ue1.setKey("resourceId");
        					ue1.setValue(task.getId());
        					list1.add(ue1);
        					String text = "";
        					if(task.getTypeDo()==null){
        						text = "您好，您发布的"+task.getTaskName()+"到期自动关闭。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。";
                			}else{
                				text = "您好，您发布的"+task.getTypeDo().getName()+"到期自动关闭。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。";
                			}
        					demo.sendAndroidUnicast(task.getUser().getDeviceToken(), "任务到期","任务到期",text, list1);
        					
        				}
        				
        				//推送结束----------
       	       			
    				   }else{
    					   //如果有未审核的任务
    					   for(UserTaskDo ut1:list){
    						   //将未审核的任务自动审核通过
    						   ut1.setStatus(3);
    						   userTaskDao.update(ut1);
    						   
    							MessageDo message1 = new MessageDo();
    		        			message1.setCreateTime(new Date());
    		        			message1.setIsRead(0);
    		        			message1.setUserId(ut1.getUser().getId());
    		        			message1.setResourceId(ut1.getTask().getId());
    		        			if(ut1.getTask().getTypeDo()==null){
    		        				message1.setTitle(ut1.getTask().getTaskGold()+"金币已到账，您提交的"+ut1.getTask().getTaskName()+"任务已被对方审核通过。");
    		        			}else{
    		        				message1.setTitle(ut1.getTask().getTaskGold()+"金币已到账，您提交的"+ut1.getTask().getTypeDo().getName()+"任务已被对方审核通过。");
    		        			}
    		        			
    		        			message1.setType(2);
    		        			messageDao.save(message1);
    		        			
    		        			 //为领取人发放金币
    		        			 UserAccountDo ua1 = userAccountDao.findUserAccount(ut1.getUser().getId());
    		    				 ua1.setGlod(ua1.getGlod()+task.getSurplusCount()*task.getTaskGold());
    		    				 userAccountDao.update(ua1);
    		    				   
    		    				//插入金币记录
		    				   	UserAccountRecordDo uar1 = new UserAccountRecordDo();
			           			uar1.setAmount(ut1.getTask().getSurplusCount()*ut1.getTask().getTaskGold());
			           			uar1.setCreateTime(new Date());
			           			uar1.setUserId(ut1.getUser().getId());
			           			uar1.setGlodType(1);
			           			uar1.setType(3);
			           			uar1.setTitle("完成任务");
			           			userService.saveAccountRecord(uar1);
    						   
    					   }
    					   //向发布任务者发送消息
    					   if(task.getTypeDo()==null){
	       	       				message.setTitle("您好，您发布的"+task.getTaskName()+"到期已停止接单。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。"+list.size()+"个任务自动审核通过。");
	       	       			}else{
	       	       				message.setTitle("您好，您发布的"+task.getTypeDo().getName()+"到期自动关闭。未消耗的"+task.getSurplusCount()+task.getTaskGold()+"金币已自动退回。还有"+list.size()+"个任务自动审核通过。");
	       	       			}
	       	       			
    				   }
    				   
    				   messageDao.save(message);
    				 	
    			   }else{
    				   
    				   //假如该任务没有剩余数量，查询是否有未审核的任务
    				   UserTaskDo ut = new UserTaskDo();
    				   ut.setTaskId(task.getId());
    				   ut.setStatus(1);
    				   List<UserTaskDo> list = userTaskDao.select(ut);
    				   //如果存在未审核的任务
    				   if(list!=null&&list.size()>0){
    					   for(UserTaskDo ut1:list){
    						   //将该用户领取的任务自动审核通过
    						   ut1.setStatus(3);
    						   userTaskDao.update(ut1);
    						   //向领取人发送消息
    							MessageDo message1 = new MessageDo();
    		        			message1.setCreateTime(new Date());
    		        			message1.setIsRead(0);
    		        			message1.setUserId(ut1.getUser().getId());
    		        			message1.setResourceId(ut1.getTask().getId());
    		        			if(ut1.getTask().getTypeDo()==null){
    		        				message1.setTitle(ut1.getTask().getTaskGold()+"金币已到账，您提交的"+ut1.getTask().getTaskName()+"任务已被对方审核通过。");
    		        			}else{
    		        				message1.setTitle(ut1.getTask().getTaskGold()+"金币已到账，您提交的"+ut1.getTask().getTypeDo().getName()+"任务已被对方审核通过。");
    		        			}
    		        			
    		        			message1.setType(2);
    		        			messageDao.save(message1);
    		        			
    		        			 //为领取人发放金币
    		        			 UserAccountDo ua1 = userAccountDao.findUserAccount(ut1.getUser().getId());
    		    				 ua1.setGlod(ua1.getGlod()+task.getSurplusCount()*task.getTaskGold());
    		    				 userAccountDao.update(ua1);
    		    				   
    		    				//插入金币记录
		    				   	UserAccountRecordDo uar1 = new UserAccountRecordDo();
			           			uar1.setAmount(ut1.getTask().getSurplusCount()*ut1.getTask().getTaskGold());
			           			uar1.setCreateTime(new Date());
			           			uar1.setUserId(ut1.getUser().getId());
			           			uar1.setGlodType(1);
			           			uar1.setType(3);
			           			uar1.setTitle("完成任务");
			           			userService.saveAccountRecord(uar1);
    						   
    					   }
    				   }
    				   
    					//将该任务置为完成
    				   task.setTaskStatus(2);
        			   taskDao.update(task);
    			   }
    		   }else{
    			   //假如任务没有超时且任务没有生育数量
    			   if(task.getSurplusCount()<=0){
    				   MessageDo msg =new MessageDo();
    				   msg.setResourceId(task.getId());
    				   msg.setUserId(task.getUser().getId());
    				   msg.setType(1);
    				   List<MessageDo> list = messageDao.select(msg);
    				   if(list==null||list.size()<=0){
    					   MessageDo message = new MessageDo();
    					   
    					   	message.setCreateTime(new Date());
	       	       			message.setIsRead(0);
	       	       			message.setUserId(task.getUser().getId());
	       	       			if(task.getTypeDo()==null){
	       	       				message.setTitle("您好，您发布的"+task.getTaskName()+"已全部完成，赶快去审核吧！");
	       	       			}else{
	       	       				message.setTitle("您好，您发布的"+task.getTypeDo().getName()+"已全部完成，赶快去审核吧！");
	       	       			}
	       	       			
	       	       			message.setType(1);
	       	       			message.setResourceId(task.getId());
	       	       			
	       	       			messageDao.save(message);
	       	       			
	       	       			
	       	       		if(task.getUser().getDeviceToken()!=null&&task.getUser().getDeviceToken().length()==64) {
	       	       			Demo demo = new Demo();
		       	       		List<UmengExtra> list1 = new ArrayList<UmengExtra>();
	    					UmengExtra ue = new UmengExtra();
	    					ue.setKey("type");
	    					ue.setValue(5);
	    					list1.add(ue);
	    					UmengExtra ue1 = new UmengExtra();
	    					ue1.setKey("resourceId");
	    					ue1.setValue(task.getId());
	    					list1.add(ue1);
	    					String text = "";
	    					if(task.getTypeDo()==null){
        						text = "您好，您发布的"+task.getTaskName()+"已全部完成，赶快去审核吧！";
                			}else{
                				text = "您好，您发布的"+task.getTypeDo().getName()+"已全部完成，赶快去审核吧！";
                			}
	    					JSONObject alert = new JSONObject();
	    					alert.put("title", "任务完成");
	    					//alert.put("subtitle", "任务完成通知");
	    					alert.put("body", text);
	    					demo.sendIOSUnicast(task.getUser().getDeviceToken(), alert,list1);
        				}
        				
        				if(task.getUser().getDeviceToken()!=null&&task.getUser().getDeviceToken().length()==44) {
        					Demo demo = new Demo();
        					List<UmengExtra> list1 = new ArrayList<UmengExtra>();
        					UmengExtra ue = new UmengExtra();
        					ue.setKey("type");
        					ue.setValue(5);
        					list1.add(ue);
        					UmengExtra ue1 = new UmengExtra();
        					ue1.setKey("resourceId");
        					ue1.setValue(task.getId());
        					list1.add(ue1);
        					String text = "";
        					if(task.getTypeDo()==null){
        						text = "您好，您发布的"+task.getTaskName()+"已全部完成，赶快去审核吧！";
                			}else{
                				text = "您好，您发布的"+task.getTypeDo().getName()+"已全部完成，赶快去审核吧！";
                			}
        					demo.sendAndroidUnicast(task.getUser().getDeviceToken(), "任务完成","任务完成",text, list1);
        					
        				}
	       	       			
    				   }
    			   }
    		   }
    		 
    	   }
       }
       
       
       UserTaskDo ut = new UserTaskDo();
       ut.setStatus(0);
       
       List<UserTaskDo> uts = userTaskDao.select(ut);
       if(uts!=null&&uts.size()>0){
    	   for(UserTaskDo t1:uts){
    		   Calendar start=Calendar.getInstance();
    		   start.setTime(t1.getCreateTime());
    		   start.add(Calendar.MINUTE,10);
    		   if(start.getTime().before(new Date())){
    			   t1.setStatus(5);
    			   userTaskDao.update(t1);
    			   
    			   TaskDo task = taskDao.findOne(t1.getTask().getId());
    			   task.setSurplusCount(task.getSurplusCount()+1);
    			   taskDao.update(task);
    			   
    			   
    		   		if(t1.getUser().getDeviceToken()!=null&&t1.getUser().getDeviceToken().length()==64) {
    		   			Demo demo = new Demo();
	       	       		List<UmengExtra> list1 = new ArrayList<UmengExtra>();
    					UmengExtra ue = new UmengExtra();
    					ue.setKey("type");
    					ue.setValue(6);
    					list1.add(ue);
    					UmengExtra ue1 = new UmengExtra();
    					ue1.setKey("resourceId");
    					ue1.setValue(t1.getTask().getId());
    					list1.add(ue1);
    					String text = "";
    					if(t1.getTask().getTypeDo()==null||t1.getTask().getTypeDo().getId()==-1){
    						text = "您好，您领取的"+t1.getTask().getTaskName()+"未及时提交已失效，快去看看其他任务吧！";
            			}else{
            				text = "您好，您领取的"+task.getTypeDo().getName()+"未及时提交已失效，快去看看其他任务吧！";
            			}
    					JSONObject alert = new JSONObject();
    					alert.put("title", "任务超时");
    					//alert.put("subtitle", "任务超时通知");
    					alert.put("body", text);
    					demo.sendIOSUnicast(t1.getUser().getDeviceToken(), alert,list1);
    				}
    				
    				if(t1.getUser().getDeviceToken()!=null&&t1.getUser().getDeviceToken().length()==44) {
    					Demo demo = new Demo();
    					List<UmengExtra> list1 = new ArrayList<UmengExtra>();
    					UmengExtra ue = new UmengExtra();
    					ue.setKey("type");
    					ue.setValue(6);
    					list1.add(ue);
    					UmengExtra ue1 = new UmengExtra();
    					ue1.setKey("resourceId");
    					ue1.setValue(t1.getTask().getId());
    					list1.add(ue1);
    					String text = "";
    					if(t1.getTask().getTypeDo()==null||t1.getTask().getTypeDo().getId()==-1){
    						text = "您好，您领取的"+t1.getTask().getTaskName()+"未及时提交已失效，快去看看其他任务吧！";
            			}else{
            				text = "您好，您领取的"+task.getTypeDo().getName()+"未及时提交已失效，快去看看其他任务吧！";
            			}
    					demo.sendAndroidUnicast(t1.getUser().getDeviceToken(), "任务超时","任务超时",text, list1);
    					
    				}
    		   }
    	   }
       }
       log.info("任务定时任务-----------------------");
        
        
     
    }
    
    

   
}
